package com.dbappsecurity.jsbridge.api;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.webkit.JavascriptInterface;
import com.dbappsecurity.jsbridge.contract.JsApiTitlebarContract;
import com.dbappsecurity.jsbridge.entity.jsGroupItems;
import com.dbappsecurity.jsbridge.webview.CompletionHandler;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;

public class JsApiTitlebar {

  private JsApiTitlebarContract mContract;
  private Handler mHandler = new Handler(Looper.getMainLooper());
  private Gson gson = new Gson();

  public JsApiTitlebar(JsApiTitlebarContract contract) {
    mContract = contract;
  }

  @JavascriptInterface
  public void buttons(Object args, CompletionHandler handler) {
    if (args == null) return;
    JSONObject jsonObject = (JSONObject) args;
    Log.i("JsApiToggle", "Arirus buttons: " + jsonObject.toString());
    final jsGroupItems items = gson.fromJson(jsonObject.toString(), jsGroupItems.class);
    mHandler.post(()->mContract.buttons(items.getItemList(),items.getType(),handler));
  }

  @JavascriptInterface
  public void menu(Object args, CompletionHandler handler) {
    if (args == null) return;
    JSONObject jsonObject = (JSONObject) args;
    Log.i("JsApiToggle", "Arirus menu: " + jsonObject.toString());
    final jsGroupItems items = gson.fromJson(jsonObject.toString(), jsGroupItems.class);
    mHandler.post(()->mContract.menu(items.getItemList(),handler));
  }

  @JavascriptInterface
  public void title(Object args, CompletionHandler handler) {
    if (args == null) return;
    JSONObject jsonObject = (JSONObject) args;
    Log.i("JsApiToggle", "Arirus title: " + jsonObject.toString());
    mHandler.post(()-> {
      try {
        mContract.title(jsonObject.getString("title"));
      } catch (JSONException e) {
        e.printStackTrace();
      }
    });
  }

  @JavascriptInterface
  public void color(Object args, CompletionHandler handler) {
    if (args == null) return;
    JSONObject jsonObject = (JSONObject) args;
    Log.i("JsApiToggle", "Arirus color: " + jsonObject.toString());
    mHandler.post(()-> {
      try {
        mContract.color(jsonObject.getInt("color"));
      } catch (JSONException e) {
        e.printStackTrace();
      }
    });
  }
}
